/**
 * File Created at 2016年5月4日
 * Copyright 2016 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */
package com.hw.one.collect.pollution.server;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 认证配置
 * @author duqunxing
 *
 */
public class Authen {

	private final ReentrantLock lock = new ReentrantLock();
	private static List<Map<String, String>> authentication = new ArrayList<Map<String,String>>(5);
	
	private Authen(){}
	
	private static Authen authen;
	
	/**
	 * 获取认证实例
	 * @return
	 */
	public static Authen getInstance(){
		if(null == authen){
			authen = new Authen();
			initConfig();
		}
		return authen;
		
	}
	/**
	 * 获取认证集合
	 * @return
	 */
	public List<Map<String, String>> getAuthentications (){
		return authentication;
	}
	/**
	 * 初始化认证信息
	 */
	private static void initConfig(){
		String src = "/auth.properties";
		InputStream is = ClassLoader.class.getResourceAsStream(src);
		Properties properties = new Properties();
		try {
			properties.load(is);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Iterator<Object> its = properties.keySet().iterator();
		while (its.hasNext()) {
			String key = (String) its.next();
			if(key.startsWith("UserPwd",3)){
				String value = properties.getProperty(key);
				String[] userPwd = value.split(",");
				Map<String, String> map = new HashMap<>(2);
				map.put("appId", userPwd[0]);
				map.put("appKey", userPwd[1]);
				authentication.add(map);
			}

		}
	}

	/**
	 * 是否认证成功
	 * @param appKey
	 * @return
     */
	public boolean isAuthen(String appId,String appKey){
		lock.lock();
		try {
			boolean isAuth = false;
			for (Map<String, String> authMap : Authen.getInstance().getAuthentications()) {
				if(appId.equals(authMap.get("appId")) && appKey.equals(authMap.get("appKey"))){
					isAuth = true;
					break;
				}
			}
			return isAuth;
		}  finally {
			lock.unlock();
		}
	}
}
